import { Module, DynamicModule } from '@nestjs/common';
import {
  getDataSourceToken,
  getRepositoryToken,
  TypeOrmModule,
} from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { CrudService } from '../common/crud.service';

@Module({})
export class GlobalCrudModule {
  static forRoot<T>(entity: new () => T): DynamicModule {
    return {
      module: GlobalCrudModule,
      imports: [TypeOrmModule.forFeature([entity])],
      providers: [
        {
          provide: CrudService,
          useFactory: (repository: Repository<T>, dataSource: DataSource) =>
            new CrudService<T>(repository, dataSource),
          inject: [getRepositoryToken(entity), getDataSourceToken()],
        },
      ],
      exports: [CrudService],
    };
  }
}
